package cn.ejiakanghu.logistics.service.impl;

import cn.hutool.core.util.ObjectUtil;
import org.apache.commons.lang3.StringUtils;
import org.linlinjava.litemall.core.lock_rfid.LockRfidUtil;
import org.linlinjava.litemall.core.lock_rfid.UnLockCabinetGoodsVo;
import org.linlinjava.litemall.db.dao.*;
import org.linlinjava.litemall.db.dao.logistics.LogisticsMapper;
import org.linlinjava.litemall.db.domain.*;
import org.linlinjava.litemall.db.util.LgBaseInfoStatConstant;
import org.linlinjava.litemall.db.util.OrderUtil;
import org.linlinjava.litemall.db.vo.locks.PickUp;
import org.linlinjava.litemall.db.vo.logistics.LogisticsGoodsTypeData;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.*;

/**
 * @author wj
 * @date 2021/11/5 17:17
 */
@Service
public class OrderStateService {
    Logger logger = LoggerFactory.getLogger(OrderStateService.class);

    @Resource
    private LitemallOrderGoodsMapper litemallOrderGoodsMapper;

    @Resource
    private LitemallOrderMapper litemallOrderMapper;

    @Resource
    private LitemallOrderItemMapper litemallOrderItemMapper;

    @Resource
    private LogisticsMapper logisticsMapper;

    @Resource
    private LockRfidUtil lockRfidUtil;

    @Resource
    private AgedmallRfidGoodsProductMapper agedmallRfidGoodsProductMapper;

    @Resource
    private AgedmallCabinetGoodsMapper agedmallCabinetGoodsMapper;

    @Resource
    private AgedmallGoodsEquMapper agedmallGoodsEquMapper;

    @Resource
    private AgedmallLgRfidGoodsCurStatMapper agedmallLgRfidGoodsCurStatMapper;







    /**
     * 修改orderGoods表状态
     * @param orderGoodsId  orderGoods表id
     * @param state  状态 LgBaseInfoStatConstant表状态
     */
    public boolean modifyOrderGoodsState(Integer orderGoodsId,Integer state){
        LitemallOrderGoods orderGoods=litemallOrderGoodsMapper.selectByPrimaryKey(orderGoodsId);
        orderGoods.setOrderGoodsStat(state);
        litemallOrderGoodsMapper.updateByPrimaryKeySelective(orderGoods);
        //更新子订单
        modifySubOrderState(orderGoods.getChildOrderId(),state);
        return true;
    }

    /**
     * 修改orderGoods表状态-批量
     * @param orderGoodsIdList  orderGoods表id
     * @param state  状态 LgBaseInfoStatConstant表状态
     */
    public boolean modifyOrderGoodsStateBatch(List<Integer> orderGoodsIdList,Integer state){
        LitemallOrderGoodsExample orderGoodsExample=new LitemallOrderGoodsExample();
        orderGoodsExample.or().andIdIn(orderGoodsIdList);
        List<LitemallOrderGoods> orderGoods=litemallOrderGoodsMapper.selectByExample(orderGoodsExample);

        LitemallOrderGoods updateGoods = new LitemallOrderGoods();
        updateGoods.setOrderGoodsStat(state);
        litemallOrderGoodsMapper.updateByExampleSelective(updateGoods,orderGoodsExample);
        //更新子订单
        modifySubOrderState(orderGoods.get(0).getChildOrderId(),state);
        return true;
    }

    /**
     * 医柜锁定的rfid变更
     */
    public void replaceCabinetGoodsRfid(List<LitemallOrderGoods> orderGoods,List<PickUp> newRfids){
        List<String> oldRfids=new ArrayList<>();
        orderGoods.forEach( rfidGoods ->{
            if(rfidGoods.getStockType()==2){
                String[] split = rfidGoods.getRfid().split(",");
                for (int i = 0; i < split.length; i++) {
                    oldRfids.add(split[i]);
                }
                //取消旧的锁定
                UnLockCabinetGoodsVo old=new UnLockCabinetGoodsVo();
                old.setRfid(oldRfids);
                lockRfidUtil.unlockCabinetGoods(old);
            }
        });
        Map<Integer,List<String>> changeMap=new HashMap<>();
        for (int i = 0; i < orderGoods.size(); i++) {
            List<String> rfids=new ArrayList<>();
            for (int j = 0; j < newRfids.size(); j++) {
                if(orderGoods.get(i).getGoodsId().equals(newRfids.get(j).getId())&&
                        orderGoods.get(i).getProductId().equals(newRfids.get(j).getSkuId())){
                    rfids.add(newRfids.get(j).getRfid());
                }
            }
            logger.debug("切换rfid:{}",orderGoods);
            logger.debug("切换rfid1:[{}]",newRfids);
            logger.debug("切换rfid2:[{}],[{}]",newRfids.get(0).getId(),newRfids.get(0).getSkuId());
            //锁定新的
            if(!rfids.isEmpty()){
                UnLockCabinetGoodsVo news=new UnLockCabinetGoodsVo();
                news.setRfid(rfids);
                lockRfidUtil.replaceLockCabinetGoods(news);
                changeMap.put(orderGoods.get(i).getId(),rfids);
            }
        }

        for(Map.Entry<Integer,List<String>> entry : changeMap.entrySet()){
            Integer mapKey = entry.getKey();
            List<String> mapValue = entry.getValue();
            for (int i = 0; i < orderGoods.size(); i++) {
                LitemallOrderGoods newOrder=orderGoods.get(i);
                if(newOrder.getId().equals(mapKey)){
                    //更新orderGoods表
                    newOrder.setRfid(StringUtils.join(mapValue,","));
                    litemallOrderGoodsMapper.updateByPrimaryKeySelective(newOrder);
                }
            }
        }


    }


    /**
     * 更新子订单状态
     * @param orderId 子订单id
     */
    public void modifySubOrderState(Long orderId,Integer orderGoodsState){
        LitemallOrderGoodsExample goodsExample=new LitemallOrderGoodsExample();
        goodsExample.or().andChildOrderIdEqualTo(orderId);
        List<LitemallOrderGoods> litemallOrderGoods = litemallOrderGoodsMapper.selectByExample(goodsExample);
        List<Integer> stateList=new ArrayList<>();
        litemallOrderGoods.forEach(orderGoods -> stateList.add(orderGoods.getOrderGoodsStat()));
        Collections.sort(stateList);
        Integer nowState=0;
        for (Integer state:stateList) {
            if(!state.equals(LgBaseInfoStatConstant.REFUSE)&&!state.equals(LgBaseInfoStatConstant.CHANGE_REFUSE)
                    &&!state.equals(LgBaseInfoStatConstant.UN_MAINTAINING)&&!state.equals(LgBaseInfoStatConstant.MAINTAINING)&&
            !state.equals(LgBaseInfoStatConstant.MAINTAIN_COMPLETE)&&!state.equals(LgBaseInfoStatConstant.STATE_EXCEPTION)){
                nowState=state;
                break;
            }
        }

        //拆离后的子订单信息
//        LitemallOrder subOrder=litemallOrderMapper.selectByPrimaryKey(orderId);
        LitemallOrderItem orderItem=litemallOrderItemMapper.selectByPrimaryKey(orderId.intValue());
        Short orderStatus=changeSubOrderState(nowState,orderItem.getGoodsType());
        if(orderGoodsState.equals(LgBaseInfoStatConstant.BUY_SENDING)||orderGoodsState.equals(LgBaseInfoStatConstant.PICK_UP_ALLOT_COMPLETE)){
            orderItem.setShipTime(LocalDateTime.now());
        }
        if(orderGoodsState.equals(LgBaseInfoStatConstant.BUY_SEND_COMPLETE)||orderGoodsState.equals(LgBaseInfoStatConstant.PICK_UP_COMPLETE)){
            orderItem.setShipArriveTime(LocalDateTime.now());
        }
        if(orderStatus!=0){
            orderItem.setOrderStatus(orderStatus);
        }
        litemallOrderItemMapper.updateByPrimaryKeySelective(orderItem);
    }


    public Short changeSubOrderState(Integer orderGoodsState,String goodsType){
        if(goodsType.equals("lease")){
            return orderGoodsStateToSubOrderStateLease(orderGoodsState).shortValue();
        }
        else {
            return orderGoodsStateToSubOrderStateSale(orderGoodsState).shortValue();
        }
    }


    /**
     * 售卖状态转换
     * case值参看 @{LgBaseInfoStatConstant}
     * @return
     */
    public static Integer orderGoodsStateToSubOrderStateSale(Integer orderGoodsState){

        switch (orderGoodsState) {
            case 10:
            case 11:
            case 12:
            case 45:
                return Integer.valueOf(OrderUtil.STATUS_PAY);
            case 46:
                return Integer.valueOf(OrderUtil.STATUS_SHIP_SELF);
            case 13:
            case 14:
            case 15:
                return Integer.valueOf(OrderUtil.STATUS_SHIP);
            case 100:
                return Integer.valueOf(OrderUtil.STATUS_REFUSED);
            default:
                return 0;
        }
    }

    /**
     * 租赁状态转换
     * @return
     */
    public static Integer orderGoodsStateToSubOrderStateLease(Integer orderGoodsState){

        switch (orderGoodsState) {
            case 10:
            case 11:
            case 12:
            case 45:
                return Integer.valueOf(OrderUtil.STATUS_PAY);
            case 46:
                return Integer.valueOf(OrderUtil.STATUS_SHIP_SELF);
            case 13:
            case 14:
            case 15:
                return Integer.valueOf(OrderUtil.STATUS_SHIP);
            case 34:
                return Integer.valueOf(OrderUtil.STATUS_RETURN);
            case 35:
                return Integer.valueOf(OrderUtil.STATUS_RETURN_SELF);
            case 80:
                return Integer.valueOf(OrderUtil.STATUS_RETURN_SUCCESS);
            default:
                return 0;
        }
    }


    /**
     * 确认收货修改rfid状态
     */
    public void confirmOrderRfidStateChange(LitemallOrderItem orderItem){
        LitemallOrderGoodsExample orderGoodsExample=new LitemallOrderGoodsExample();
        orderGoodsExample.or().andChildOrderCodeEqualTo(orderItem.getChildOrderCode());
        List<LitemallOrderGoods> orderGoodsList = litemallOrderGoodsMapper.selectByExample(orderGoodsExample);

        //医柜Rfid
        List<String> cabinetRfidList=new ArrayList<>();
        //链条Rfid
        List<String> chainRfidList=new ArrayList<>();



            for (int i = 0; i < orderGoodsList.size(); i++) {
                LitemallOrderGoods litemallOrderGoods = orderGoodsList.get(i);
                //链条锁
                if(litemallOrderGoods.getStockType()==1){
                    String[] split = litemallOrderGoods.getRfid().split(",");
                    chainRfidList.addAll(Arrays.asList(split));
                }
                //医柜锁
                else if(litemallOrderGoods.getStockType()==2){
                    String[] split = litemallOrderGoods.getRfid().split(",");
                    cabinetRfidList.addAll(Arrays.asList(split));
                }
            }

            //如果有医柜
            if(!cabinetRfidList.isEmpty()){
                AgedmallRfidGoodsProductExample goodsProductExample=new AgedmallRfidGoodsProductExample();
                goodsProductExample.or().andRfidIn(cabinetRfidList);
                List<AgedmallRfidGoodsProduct> list = agedmallRfidGoodsProductMapper.selectByExample(goodsProductExample);
                AgedmallRfidGoodsProduct rfidGoodsProduct=new AgedmallRfidGoodsProduct();


                List<Long> idList=new ArrayList<>();
                list.forEach( goodsProduct -> idList.add(goodsProduct.getId()));
                AgedmallCabinetGoodsExample cabinetGoodsExample=new AgedmallCabinetGoodsExample();
                cabinetGoodsExample.or().andGoodsRfidIdIn(idList);
                AgedmallCabinetGoods cabinetGoods=new AgedmallCabinetGoods();



                AgedmallLgRfidGoodsCurStatExample goodsCurStatExample=new AgedmallLgRfidGoodsCurStatExample();
                goodsCurStatExample.or().andTypeEqualTo(2).andRfidIn(cabinetRfidList);
                AgedmallLgRfidGoodsCurStat goodsCurStat=new AgedmallLgRfidGoodsCurStat();
                if(orderItem.getGoodsType().equals("lease")){
                    rfidGoodsProduct.setStat(3);
                    cabinetGoods.setStat(5);
                    goodsCurStat.setCurStat(2);
                }
                else{
                    rfidGoodsProduct.setStat(4);
                    cabinetGoods.setStat(2);
                    goodsCurStat.setCurStat(9);
                }
                agedmallRfidGoodsProductMapper.updateByExampleSelective(rfidGoodsProduct,goodsProductExample);
                agedmallCabinetGoodsMapper.updateByExampleSelective(cabinetGoods,cabinetGoodsExample);
                agedmallLgRfidGoodsCurStatMapper.updateByExampleSelective(goodsCurStat,goodsCurStatExample);
            }

            //链条锁
            if(!chainRfidList.isEmpty()){
                List<Long> goodsEquList=new ArrayList<>();
                chainRfidList.forEach(chain -> goodsEquList.add(Long.parseLong(chain)));
                AgedmallGoodsEquExample goodsEquExample=new AgedmallGoodsEquExample();
                goodsEquExample.or().andTypeEqualTo(0).andEquIdIn(goodsEquList);
                AgedmallGoodsEqu goodsEqu=new AgedmallGoodsEqu();

                AgedmallLgRfidGoodsCurStatExample goodsCurStatExample=new AgedmallLgRfidGoodsCurStatExample();
                goodsCurStatExample.or().andTypeEqualTo(1).andRfidIn(chainRfidList);
                AgedmallLgRfidGoodsCurStat goodsCurStat=new AgedmallLgRfidGoodsCurStat();


                if(orderItem.getGoodsType().equals("lease")){
                    goodsEqu.setState(3);
                    goodsCurStat.setCurStat(2);
                }
                else{
                    goodsEqu.setState(5);
                    goodsCurStat.setCurStat(9);
                }
                agedmallGoodsEquMapper.updateByExampleSelective(goodsEqu,goodsEquExample);
                agedmallLgRfidGoodsCurStatMapper.updateByExampleSelective(goodsCurStat,goodsCurStatExample);
            }


    }


}
